package services

import (
	"demo/enmu"
	"demo/models"
	"demo/pkg/database"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gonum.org/v1/gonum/floats"
)

func GenerateAdminInfo(c *gin.Context) {
	resp := models.GetDefaultResp()
	bills, err := database.GetAllBills()
	if err != nil {
		logrus.Error("failed to query electricity bills: ", err)
		return
	}

	if len(bills) == 0 {
		logrus.Error("no bills found")
		return
	}

	var usage []float64
	var amounts []float64
	for _, bill := range bills {
		usage = append(usage, float64(bill.ElectricityUsage))
		amounts = append(amounts, float64(bill.Amount))
	}

	totalUsage := floats.Sum(usage)
	totalAmount := floats.Sum(amounts)

	formattedTotalUsage, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", totalUsage), 64)
	formattedTotalAmount, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", totalAmount), 64)

	report := &models.AdminInfo{
		TotalUsage:  formattedTotalUsage,
		TotalAmount: formattedTotalAmount,
	}
	resp.Data = report
	c.JSON(http.StatusOK, resp)

}

func GenerateAdminReport(c *gin.Context) {
	resp := models.GetDefaultResp()
	bills, err := database.GetAllBills()
	if err != nil {
		logrus.Error("failed to fetch electricity bills:", err)
		resp.Code, resp.Msg = enmu.BAD_REGIRSTER_INFO_CODE, enmu.BAD_REGIRSTER_INFO_MSG
		c.JSON(http.StatusBadRequest, resp)
		return
	}

	// 创建一个 map 用于统计每个月的用电量
	monthlyElectricity := make(map[string]float32)

	// 遍历账单，按月统计用电量
	for _, bill := range bills {
		month := bill.BillDate.Format("2006-01")
		monthlyElectricity[month] += bill.ElectricityUsage
	}

	// 确保所有月份都在结果中，没有的月份设置用电量为0
	addMissingMonths(monthlyElectricity)

	resp.Data = monthlyElectricity
	c.JSON(http.StatusOK, resp)

}
